import { ScrollView, View, Text, Image } from '@tarojs/components';
import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { connect } from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import Blank from '@/pages/common/blank';
import api from 'api';
import nonesImg from '@/assets/image/none/nones.png'
import mqbgImg from '@/assets/image/my/mq_bg.png'
import dateImg from '@/assets/image/my/date.png'
import numImg from '@/assets/image/my/num.png'
import titleImg from '@/assets/image/my/title.png'
import writeImg from '@/assets/image/my/write.png'
import writeingImg from '@/assets/image/my/writeing.png'

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      pageNum: 0,
      totalPages: 0,
      refresherTriggered: false,
      questionList: []
    };
  }

  componentDidMount() { }

  componentDidShow() {
    let { user } = Taro.getStorageSync('b2b-wechat@login')
    if (user) {
      this.getList()
    }
  }

  componentWillUnmount() { }

  _onScrollToLower = () => {
    let { totalPages, pageNum } = this.state;
    let num = pageNum + 1;
    if (num == totalPages) return;
    this.setState({ pageNum: num },
      () => {
        this.getList()
      }
    )
  };

  async getList() {
    let selectDistance = Taro.getStorageSync('selectDistance');
    let { user } = Taro.getStorageSync('b2b-wechat@login');
    let { pageNum } = this.state;
    let params = {
      pageNum,
      userId: user?.id || '',
      scope: selectDistance.code
    }
    let result = await api.investigationController.findInvestList(params);
    if (result.success) {
      let list = JSON.parse(JSON.stringify(this.state.questionList));
      if (pageNum == 0) {
        this.setState({
          questionList: result.data.rows,
          totalPages: result.data.total
        })
      } else {
        let newList = list.concat(result.data.rows,);
        this.setState({
          questionList: newList,
          totalPages: result.data.total
        })
      }
    }
  }

  _onRefresherRefresh = () => {
    const { refresherTriggered } = this.state;
    if (refresherTriggered) return;
    this.setState({
      refresherTriggered: true,
    });
    this.setState({ pageNum: 0, questionList: [] },
      () => {
        this.getList()
      }
    )
    setTimeout(() => {
      this.setState({
        refresherTriggered: false,
      });
    }, 2000);
  };

  renderList(list) {
    let ViewItem = [];
    list.map((item, index) => {
      const currentTimestamp = new Date().getTime(); //当前日期时间戳
      let regEx = new RegExp('\\-', 'gi'); //转换时间戳
      let statrTime = item.startDate.replace(regEx, '/'); //开始时间
      let statrTime1 = Date.parse(statrTime);
      let endTime = item.endDate.replace(regEx, '/'); //结束时间
      let endTime1 = Date.parse(endTime);
      ViewItem.push(
        <View
          className='content'
          onClick={() => {
            if (parseFloat(statrTime1) > parseFloat(currentTimestamp)) {
              Taro.showToast({
                title: '该问卷答题时间未开始，不可进行操作！',
                icon: 'none',
                duration: 2000,
              });
              return
            } else if (
              parseFloat(endTime1) < parseFloat(currentTimestamp) &&
              item.type == 0
            ) {
              Taro.showToast({
                title: '该问卷答题时间已结束，不可进行操作！',
                icon: 'none',
                duration: 2000,
              });
              return
            } else {
              Taro.setStorageSync('questionDetail', item);
              Taro.navigateTo({
                url: '/pages/package-A/question-survery/list/index'
              })
            }
          }}>
          <Image className='mq_bg' mode="widthFix" src={mqbgImg} />
          <View style={{ padding: '10px' }}>
            <Text className='title'>
              {item.investigationName}
            </Text>
          </View>
          <View className='detail'>
            <View className='info'>
              <Image className='date' mode="widthFix" src={dateImg} />
              <Text className='infos'>{item.startDate}~{item.endDate}</Text>
              {/* <Text className='infos'>{item.endDate.substring(0, 10)}</Text> */}
            </View>
          </View>
          <View className='detail'>
            <View className='info'>
              <Image className='date' mode="widthFix" src={titleImg} />
              <Text className='infos'>共{item.questionCount}道题</Text>
            </View>
            <View className='info'>
              <Image className='date' mode="widthFix" src={numImg} />
              <Text className='infos'>{item.userCount}人已参与</Text>
            </View>
          </View>
          {item.type == 1 ? (
            <Image className='write' mode="widthFix" src={writeImg} />
          ) : item.type == 0 &&
            parseFloat(statrTime1) < parseFloat(currentTimestamp) &&
            parseFloat(endTime1) > parseFloat(currentTimestamp) ? (
            <Image className='write' mode="widthFix" src={writeingImg} />
          ) : parseFloat(endTime1) < parseFloat(currentTimestamp) ? (
            <View className='endBox'>
              <Text className='endText'>
                已结束
              </Text>
            </View>
          ) : parseFloat(statrTime1) > parseFloat(currentTimestamp) ? (
            <View className='endBox'>
              <Text className='endText'>
                未开始
              </Text>
            </View>
          ) : null}
        </View>
      )
    })
    return ViewItem;
  }

  render() {
    let { refresherTriggered, questionList, pageNum, totalPages } = this.state;
    return (
      <ScrollView
        className="packageAQuestionSurvery"
        scrollY
        onScrollToLower={this._onScrollToLower}
        refresherEnabled={true}
        refresherTriggered={refresherTriggered}
        onRefresherPulling={this._onRefresherRefresh}>
        {
          questionList.length > 0 ?
            this.renderList(questionList) :
            <Blank
              content="暂无问卷调查信息~"
              img={nonesImg}
              imgStyle={{ width: '400rpx', height: '400rpx' }}
              textStyle={{
                fontSize: '32rpx', color: '#999999', textAlign: 'center', marginTop: '40rpx'
              }}
            />
        }
        {questionList.length != 0 && pageNum + 1 != totalPages && <View className="status">加载中</View>}
        {
          questionList.length != 0 && pageNum + 1 == totalPages && (
            <View className="status">没有更多了</View>
          )
        }
      </ScrollView>
    );
  }
}
